/*
 * @Description: 公交线路详情页面。首末班时间、票价、公告单独获取协议
 * @Author: yingying.fan
 * @Date: 2019-05-14 18:47:19
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-05-28 18:30:43
 */
<template>
  <div>
    <!-- 标题栏 -->
    <title-bar
      :titleText="titleName"
      :needSetNextDomHeight="false"
      ref="titlebar"
    >
      <div
        slot="right"
        v-if="routeInfo"
        class="title-right"
      >
        <i
          :class="['iconfont',isCollected?'icon-shoucang1 route-collected-star':'icon-shoucang']"
          @click="changeCollection"
        ></i>
        <i
          v-if="showMap"
          class="iconfont icon-ditu-"
          @click="goToMapPage"
        ></i>
      </div>
    </title-bar>
    <!-- 公交信息部分 -->
    <div
      class="flex-v"
      ref="page"
    >
      <!-- 黄色提示条 -->
      <div
        class="fontsize28 yellow-hint"
        v-show="yellowHintText"
      >{{yellowHintText}}</div>
      <!-- 公告部分 -->
      <notice
        v-if="noticeModel"
        :notice="noticeModel"
      ></notice>
      <!-- 线路信息，票价，首末班 -->
      <route-header :routeInfo="routeInfo"></route-header>
      <!-- 车辆距离信息 -->
      <distance-list
        :routeInfo="routeInfo"
        :distanceList="distanceList"
      ></distance-list>
      <!-- 定位小三角 -->
      <route-triangle v-if="routeInfo"></route-triangle>
      <!-- 竹节图 -->
      <route-line
        class="flex1"
        ref="routeline"
        :busStationList="busStationList"
        :routeBusObject="routeBusObject"
      />
      <!-- @selectStation="setSelectedStaion" -->
      <banner
        :bannerEnName="bannerName"
        height="2.9333rem"
        width="2.9333rem"
        class="banner-line"
      ></banner>
    </div>
    <!-- 底部按钮栏 -->
    <route-footer ref="footer"></route-footer>
  </div>
</template>

<script>
import { getUrlParams } from 'vue-xiaobu-utils'
import { setRouteCollected, isRouteCollected } from '@/utils/CollectionUtils.js'
import { getCurrentPosition } from '@/utils/LocationUtils.js'
import TitleBar from '@/components/titlebar/TitleBar'
import Notice from '../components/Notice'
import RouteHeader from '../components/RouteHeader'
import DistanceList from '../components/DistanceList'
import RouteTriangle from '../components/RouteTriangle'
import RouteLine from '../components/RouteLine'
import RouteFooter from '../components/RouteFooter'
import { BannerWithCloseNoSlick, LoadingPop } from 'vue-xb-ui-depot'
import {
  getRouteInfo,
  getRouteNotice,
  getBusListByLocation,
  getBusListBySameId,
  getBusPrice,
  getFirstAndLastBusTime,
  getNextBusTime
} from '../api/api.js'
import { resetAllAttentionData, stationIsAttention } from '../api/busPlugin'
import { clear } from '../api/busPositionUtils'
const PAGE_NORMAL = 0 // 正常无错误
const PAGE_LOCATION_ERROR = 1 // 页面报错等级
const PAGE_POST_ERROR = 2
export default {
  components: {
    'title-bar': TitleBar,
    'notice': Notice,
    'route-header': RouteHeader,
    'distance-list': DistanceList,
    'route-triangle': RouteTriangle,
    'route-line': RouteLine,
    'route-footer': RouteFooter,
    'banner': BannerWithCloseNoSlick
  },
  data() {
    return {
      showMap: window.openMap !== false,
      longitude: null, // 当前定位的经度
      latitude: null, // 当前定位的纬度
      pageErrorType: PAGE_NORMAL, // 错误类型
      // 广告名称
      bannerName: window.APP_BUSROUTE_DETAIL,
      routeId: null, // 线路Id
      direction: 1, // 方向
      routeName: '', // 线路名称
      routeInfo: null, // 公交数据信息
      noticeModel: null, // 线路公告
      isCollected: false, // 是否已收藏
      busStationList: [], // 公交站点信息
      distanceList: null, // 最近车辆信息
      routeBusObject: {}, // 将公交列表数据按照站点分组
      busRepeatTimer: null, // 获取实时公交计时器
      busRepeatTime: window.prodInApp ? 8000 : 3000000 // 获取实时公交时间间隔
    }
  },
  computed: {
    selectedIndex() {
      return this.$store.getters.selectedIndex
    },
    selectedStation() {
      return this.$store.getters.selectedStation
    },
    titleName() {
      if (escape(this.routeName).indexOf('%u') < 0) {
        // 路线名中如果没有中文则加上路
        return `${this.routeName}路`
      }
      return this.routeName
    },
    endStaion() {
      return this.busStationList && this.busStationList[this.busStationList.length - 1]
    },
    // 错误提示语
    yellowHintText() {
      switch (this.pageErrorType) {
        case PAGE_LOCATION_ERROR:
          return '获取定位失败'
        case PAGE_POST_ERROR:
          return '网络开小差了'
        default:
          return ''
      }
    }
  },
  mounted() {
    // BUS_DIRECTION=1&NAME=11%E8%B7%AF&ID=1011
    LoadingPop.show()
    this.$nextTick(() => {
      this.setPageHeight()
    })
    let params = getUrlParams()
    this.routeId = params['ID']
    if (this.routeId) {
      this.direction = parseInt(params['BUS_DIRECTION'])
      this.routeName = params['NAME']
      this.getMyPosition().then(result => {
        console.log('~~~getMyPosition~~~', result)
        this.getRouteStationInfo()
      })
      this.addEventBus()
      window.onResume = () => {
        console.log('~~~onResume~~~')
        this.setSelectedStaion()
      }

      window.onPause = () => {
        console.log('~~~onPause~~~')
        this.clearBusRepeatTimer()
      }

      // 底层触发了上车提醒和下车提醒时调用的页面js函数
      window.onAttentionTaskFired = () => {
        this._onAttentionTaskFired()
      }
    }
  },
  methods: {
    addEventBus() {
      // 监听换向
      this.$EventBus.$on('changeDirection', () => {
        LoadingPop.show()
        clear()
        // this.direction = this.direction === 1 ? 2 : 1
        if (this.direction === this.routeInfo.directionList[0]) {
          this.direction = this.routeInfo.directionList[1]
        } else {
          this.direction = this.routeInfo.directionList[0]
        }
        this.getRouteStationInfo()
      })
      // TODO:监听刷新事件(站点选择，设置了上下车提醒后)
      this.$EventBus.$on('refreshDataWithoutPop', () => {
        console.log('~~~refreshDataWithoutPop~~~')
        this.setSelectedStaion()
        // this.getNextBusTime()
      })
      // 监听刷新事件(底部刷新按钮)
      this.$EventBus.$on('refreshData', () => {
        console.log('~~~refreshData~~~')
        LoadingPop.show()
        if (this.routeInfo) {
          this.setSelectedStaion()
        } else {
          this.getRouteStationInfo()
        }
        // this.getNextBusTime()
      })
    },
    setPageErrorType(errorType) {
      if (this.pageErrorType !== PAGE_LOCATION_ERROR) {
        this.pageErrorType = errorType
      }
    },
    // 获取我的定位
    async getMyPosition() {
      try {
        let res = await getCurrentPosition(this, false)
        this.setPageErrorType(PAGE_NORMAL)
        this.longitude = res.longitude
        this.latitude = res.latitude
        return true
      } catch (error) {
        this.setPageErrorType(PAGE_LOCATION_ERROR)
        this.$toastMsg(error.message)
        // if (error.code === LOCATION_ERROR.GPS_NOT_OPEN) {
        //   this.isOpenGPS = false
        // } else {
        //   this.$toastMsg(error.message)
        // }
        this.longitude = null
        this.latitude = null
        return false
      }
    },
    // 获取站点列表
    getRouteStationInfo() {
      getRouteInfo(this.routeId, this.direction, this.selectedStation).then(res => {
        // 为了确保换向后车辆信息和距离信息可以重置
        this.setPageErrorType(PAGE_NORMAL)
        this.distanceList = null
        this.routeBusObject = {}
        // 获取线路信息之后将竹节图的scrollLeft置为0
        if (this.$refs.routeline) {
          this.$refs.routeline.$el.scrollLeft = 0
        }
        this.routeInfo = res.routeInfo
        this.busStationList = res.stationList
        this.$store.dispatch('fetchRouteInfo', this.routeInfo)
        // 设置默认选中的站点
        this.setDefaultSelectedStation(res.selectedIndex, res.selectedStation)
        this.isRouteCollected()
        this.getHeaderInfo()
        this.setSelectedStaion()
      }).catch(() => {
        // 线路信息获取失败也要去掉等待遮罩
        this.setPageErrorType(PAGE_POST_ERROR)
        LoadingPop.hide()
      })
    },
    // 设置默认选中的站点
    setDefaultSelectedStation(index, station) {
      if (index > -1) {
        this.$store.dispatch('fetchSelectedIndex', index)
        this.$store.dispatch('fetchSelectedStation', station)
        this.$refs.routeline.scrollToCenter()
      } else if (this.longitude === null) {
        this.$store.dispatch('fetchSelectedIndex', 0)
        this.$store.dispatch('fetchSelectedStation', this.busStationList[0])
      }
    },
    async isRouteCollected() {
      try {
        this.isCollected = await isRouteCollected(this.routeId, this.direction)
      } catch (error) {

      }
    },
    // 获取头部信息展示
    getHeaderInfo() {
      getRouteNotice(this.routeId, this.direction).then(noticeModel => {
        this.noticeModel = noticeModel
      })
      getBusPrice(this.routeId, this.direction).then(price => {
        // this.routeInfo.setPrice(price)
        this.$set(this.routeInfo, 'price', price)
      })
      getFirstAndLastBusTime(this.routeId, this.direction).then(timeObj => {
        // this.routeInfo.setStartTime(timeObj.firstTime)
        // this.routeInfo.setEndTime(timeObj.lastTime)
        this.$set(this.routeInfo, 'startTime', timeObj.firstTime)
        this.$set(this.routeInfo, 'endTime', timeObj.lastTime)
      })
      // this.getNextBusTime()
    },
    async getNextBusTime() {
      try {
        let nextTime = await getNextBusTime(this.routeId, this.direction)
        // this.routeInfo.setNextTime(nextTime)
        this.$set(this.routeInfo, 'nextTime', nextTime)
      } catch (error) {
      }
    },
    // 获取公交列表计时器
    async getBusListByTimer() {
      this.clearBusRepeatTimer()
      // 如果app在后台则停止计时器
      console.log('~~~window.pause~~~', window.pause)
      if (window.pause) {
        return
      }

      try {
        await resetAllAttentionData(this)
        this.busStationList.map((busStation, index) => {
          busStation.setStationAttention(stationIsAttention(busStation))
          // 每次hasAttention不一致时都要刷新重新set站点列表
          if (busStation.hasAttention !== this.busStationList[index].hasAttention) {
            this.$set(this.busStationList, index, busStation)
          }
        })
      } catch (error) {
      } finally {
        this.getBusList().then(() => {
          LoadingPop.hide()
          this.busRepeatTimer = setTimeout(this.getBusListByTimer, this.busRepeatTime)
        }).catch(() => {
          LoadingPop.hide()
          this.busRepeatTimer = setTimeout(this.getBusListByTimer, this.busRepeatTime)
        })
      }
    },
    clearBusRepeatTimer() {
      if (this.busRepeatTimer) {
        clearTimeout(this.busRepeatTimer)
        this.busRepeatTimer = null
      }
    },
    // 获取公交列表
    async getBusList() {
      this.getNextBusTime()
      let lastStation = null
      try {
        lastStation = this.busStationList[this.selectedIndex - 1]
      } catch (error) {
      }
      try {
        let res
        // 定位获取失败或者有默认选中的站点就走通过站点sameId获取车辆信息的协议
        // 否则就走通过定位获取车辆信息的协议
        if (this.selectedStation) {
          res = await getBusListBySameId(
            this.routeId,
            this.direction,
            this.selectedStation,
            lastStation,
            this.endStaion
          )
        } else {
          res = await getBusListByLocation(
            this.routeId,
            this.direction,
            this.longitude,
            this.latitude,
            this.busStationList
          )
          this.setDefaultSelectedStation(res.selectedIndex, res.selectedStation)
        }
        this.setPageErrorType(PAGE_NORMAL)
        this.routeBusObject = res.routeBusObject
        this.distanceList = res.distanceList
        return true
      } catch (error) {
        this.setPageErrorType(PAGE_POST_ERROR)
        // 车辆数据未返回或返回超时，提示‘暂无车辆信息’
        this.distanceList = null
        throw error
      }
    },
    // 计算页面主区域高度
    setPageHeight() {
      let titleHeight = this.$refs.titlebar.$el.offsetHeight
      let footerHeight = this.$refs.footer.$el.offsetHeight
      if (titleHeight > 0 && footerHeight > 0 && this.$refs.page) {
        let widgetHeight = titleHeight + footerHeight
        this.$refs.page.style.height = 'calc(100% - ' + widgetHeight + 'px)'
      } else {
        setTimeout(this.setPageHeight, 200)
      }
    },
    // 选中站点改变需要重新获取该站点的公交列表数据
    setSelectedStaion() {
      this.getBusListByTimer()
      // this.addRouteLineScrollTimer()
    },
    async changeCollection() {
      let {
        routeId,
        direction,
        routeName,
        startStation,
        endStation,
        startTime,
        endTime,
        price
      } = this.routeInfo
      let state = await setRouteCollected(
        this.isCollected,
        routeId,
        direction,
        routeName,
        startStation,
        endStation,
        startTime,
        endTime,
        price
      )
      this.isCollected = state
      let toastMsg, recordId
      if (state) {
        toastMsg = '收藏成功'
        recordId = 'bus_line_fav'
      } else {
        toastMsg = '取消收藏'
        recordId = 'bus_line_unfav'
      }
      this.$toastMsg(toastMsg)
      // 埋点
      this.$ThirdParty.then(thirdparty => {
        thirdparty.doRecordEvent(
          recordId,
          JSON.stringify({ LINE: this.routeId }),
          1,
          function () { },
          function (err) {
            console.log(err)
          }
        )
      })
    },
    goToMapPage() {
      this.$System.then(System => {
        System.openBusLineMap(
          parseInt(this.routeId),
          parseInt(this.direction),
          this.selectedStation.sameId,
          () => {
            console.log('打开地图成功')
          },
          err => {
            console.log(err)
          }
        )
      })
    },
    _onAttentionTaskFired() {
      // TODO: 每次底层提示之后，重新获取一遍上车和下车提醒数据
      this.setSelectedStaion()
    }
  }
}
</script>
<style>
/* 隐藏滚动条 */
div::-webkit-scrollbar {
  display: none;
}
.title-right {
  position: absolute;
  right: 0;
  overflow: hidden;
  font-size: 0;
}
.title-right > i {
  display: inline-block;
  overflow: visible;
  width: 50px;
  height: 50px;
  line-height: 50px;
  padding: 25px;
  font-size: 46px;
  vertical-align: middle;
  text-align: center;
}
.route-collected-star {
  color: #ff9938;
}
.banner-line {
  position: absolute !important;
  bottom: 1.44rem;
  right: 0.4rem;
  z-index: 15;
}
.banner-line .adCloseBtn-line {
  /* width: 0.346667rem;
  height: 0.346667rem;
  position: absolute;
  top: -0.173333rem;
  right: -0.173333rem;
  z-index: 200; */
  top: -0.573333rem !important;
  right: -0.573333rem !important;
  padding: 0.4rem;
}
.yellow-hint {
  width: 100%;
  height: 60px;
  line-height: 60px;
  text-align: center;
  background-color: #ff9938;
  color: #ffffff;
}
</style>
